class MeshBoundary:
    def __init__(self, faceVets, faceIndice, wires):
        self.segMap0 = {}
        self.segMap1 = {}
        self.faceVets = faceVets
        self.faceIndice = faceIndice
        self.wires = wires

    def parser(self):
        for trig in self.faceIndice:
            self.addSegment2Map0(trig[0], trig[1])
            self.addSegment2Map0(trig[1], trig[2])
            self.addSegment2Map0(trig[2], trig[0])
        self.createMap1()
        wires = []
        for w in self.wires:
            oldStartIndex = None
            oldEndIndex = None
            for e in w.OrderedEdges:
                vertexes = e.Vertexes
                if(len(vertexes) > 1):
                    print('findIndex:', e.firstVertex().Point, e.lastVertex().Point)
                    startIndex = self.findIndex(e.firstVertex().Point)
                    endIndex = self.findIndex(e.lastVertex().Point)
                    if(oldEndIndex != None):
                        if(oldEndIndex != startIndex):
                            break
                    if(startIndex != None):
                        wire = self.getWireFromStart(startIndex, endIndex)
                        print('wire:', wire)
                        if(wire):
                            wires.append(wire)
                    oldEndIndex = endIndex

        return wires
                

    def findIndex(self, point):
        index = 0
        for vet in self.faceVets:
            if(point.isEqual(vet, 1e-6)):
                return index
            index += 1
        return None

    def addSegment2Map0(self, index0, index1):
        trigName = getTrigName(index0, index1)
        if(trigName in self.segMap0):
            self.segMap0.pop(trigName, None)
        else:
            self.segMap0[trigName] = (index0, index1)

    def createMap1(self):
        for value in self.segMap0.values():
            self.segMap1[value[0]] = value
        self.segMap0.clear()

    def getWireFromStart(self, startIndex, endIndex):
        index = startIndex
        wire = []
        flag = False
        #print('getWireFromStart:', startIndex, endIndex, self.segMap1)
        while(index in self.segMap1):
            wire.append(self.faceVets[index])
            oldIndex = index
            index = self.segMap1[index][1]
            if not flag:
                self.segMap1.pop(oldIndex, None)
                flag = True
            if(index == startIndex or index == endIndex):
                break

        wire.append(self.faceVets[index])
        if(len(wire) < 2):
            return None
        else:
            return wire



def getTrigName(p0, p1):
    small = None
    big = None
    if p0 < p1:
        small = p0
        big = p1
    else:
        small = p1
        big = p0
    return str(small) + '_' + str(big)
